#!/usr/bin/python
# Copyright (c) 2010-, WangFei, Cloud Team, CGCL,
# All rights reserved.
# This program return the status of job.
# Using format is as follow:
#        python jobstatus master_ip master_ip_root_password "mpi_job_execute_argv"
# For example:
#        python jobstatus 192.168.226.167 passw0rd "mpirun -machinefile /home/cgcl/machine -np 2 /home/cgcl/cpi"

import os, sys
import paramiko

def get_job_status(ip,username,password,ssh_port,command):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    ip=master_address
    client.connect((ip), username=(username), password=(password), port=(ssh_port))	
    stdin,stdout,stderr = client.exec_command( "ps ax | grep \"" + command + "\"" )
    tmp =  stdout.read()
    flag = 0
    for ans in tmp.split("\n"):
        for t in ans.split(" "):
            if t == command:
                flag = 1
                break
        if flag: 
            break
    print flag
    client.close()
    return flag
	
if __name__ == "__main__":
    argv_cnt = len(sys.argv)
    if argv_cnt != 4:
        print "Command format error. Please Using As follow:\n"
        print "       python jobstatus master_ip master_ip_root_password mpi_job_execute_argv"
        sys.exit(0)
    ssh_port=22
    username="root"
    master_address = sys.argv[1]
    password = sys.argv[2]
    command = sys.argv[3]
    if 0 == get_job_status(master_address,username,password,ssh_port,command):
        print "Job is Over."
        sys.exit(0)
    else:
        print "Job is Running."
        sys.exit(1)


